package com.yjd.back.user;

import com.yjd.comm.base.control.BaseControl;
import com.yjd.comm.base.control.MobileBaseControl;
import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.base.model.PagerHtmlModel;
import com.yjd.comm.enums.CreditIndustryLevel;
import com.yjd.comm.enums.StagesStatusEnum;
import com.yjd.comm.order.model.OrderModel;
import com.yjd.comm.order.model.OrderProjectModel;
import com.yjd.comm.order.service.IOrderProjectService;
import com.yjd.comm.order.service.IOrderService;
import com.yjd.comm.project.model.ProjectShowInfo;
import com.yjd.comm.project.service.IProjectService;
import com.yjd.comm.repayment.dto.OverdueDto;
import com.yjd.comm.repayment.dto.RepaymentDto;
import com.yjd.comm.repayment.model.RepaymentDataModel;
import com.yjd.comm.repayment.service.IRepaymentDataService;
import com.yjd.comm.user.dto.UserSession;
import com.yjd.comm.user.service.IUserService;
import com.yjd.comm.util.*;
import com.yjd.comm.zhima.model.ZhimaCreditDataModel;
import com.yjd.comm.zhima.service.IZhimaCreditService;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * Created by yjd-wap on 2017/7/12.
 */

@Controller
@Scope("prototype")
@RequestMapping("/order/")
public class OredrControl extends BaseControl {

    @Resource
    private IOrderService orderService;

    @Resource
    private IOrderProjectService orderProjectService;

    @Resource
    private IProjectService projectService;

    @Resource
    IRepaymentDataService repaymentDataService;

    @Resource
    IUserService userService;

    @Resource
    private IZhimaCreditService zhimaCreditService;

    /**
     * 订单列表
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("list")
    public String list() throws Exception {
        Map<String, Object> paramMap = ServletUtil.getPageParameterMap(request);
        paramMap.put("sort", " create_time desc ");
        PagerHtmlModel pager = PagerUtil.getPagerHtmlModel(
                orderService.getOrderInfoList(paramMap),
                paramMap, ServletUtil.getUrl("/order/list"));

        OrderModel om = null;
        for (Object obj : pager.getPagerModel().getDataList()) {
            om = (OrderModel) obj;
            om.getStrMap().put("status", StagesStatusEnum.parse(om.getStatus()).getLabel());
            om.getStrMap().put("create_time", DateUtil.timestampToDateString(om.getCreate_time(), DateUtil.PATTERN_yyyy_MM_dd_HH_mm_ss));
            if (StagesStatusEnum.MERCHANT_CANCEL.getCode() == om.getStatus().intValue()) {
                om.getStrMap().put("confirm_time", DateUtil.timestampToDateString(om.getApprove_refund_time(), DateUtil.PATTERN_yyyy_MM_dd_HH_mm_ss));
            } else {
                om.getStrMap().put("confirm_time", DateUtil.timestampToDateString(om.getConfirm_time(), DateUtil.PATTERN_yyyy_MM_dd_HH_mm_ss));
            }
            om.getStrMap().put("clear_date", DateUtil.timestampToDateString(om.getClear_date(), DateUtil.PATTERN_yyyy_MM_dd));
            om.getStrMap().put("order_amount", NumberUtil.formatNumber(om.getOrder_amount()));
            om.getStrMap().put("loan_amount", NumberUtil.formatNumber(om.getLoan_amount()));
        }

        request.setAttribute("pager", pager);
        return "order.list";
    }

    @RequestMapping("detail/{order_id}")
    public String detail(@PathVariable("order_id") Long order_id) throws Exception {
        if (order_id == null) {
            FrameUtil.throwBaseException1("请输入正确参数");
        }

        OrderModel orderModel = orderService.getModelById(order_id, DbWREnums.READ);
        if (orderModel == null) {
            FrameUtil.throwBaseException1("订单不存在");
        }

        if (StagesStatusEnum.MERCHANT_CANCEL.getCode() == orderModel.getStatus().intValue()) {
            orderModel.getStrMap().put("confirm_time", DateUtil.timestampToDateString(orderModel.getApprove_refund_time(), DateUtil.PATTERN_yyyy_MM_dd_HH_mm_ss));
            orderModel.getStrMap().put("clear_date", DateUtil.timestampToDateString(orderModel.getApprove_refund_time(), DateUtil.PATTERN_yyyy_MM_dd));

        } else {
            orderModel.getStrMap().put("confirm_time", DateUtil.timestampToDateString(orderModel.getConfirm_time(), DateUtil.PATTERN_yyyy_MM_dd_HH_mm_ss));
            orderModel.getStrMap().put("clear_date", DateUtil.timestampToDateString(orderModel.getClear_date(), DateUtil.PATTERN_yyyy_MM_dd));
        }
        List<OrderProjectModel> orderProjectModelList = orderProjectService.getModelList(FrameUtil.newHashMap("order_id", order_id), DbWREnums.READ);

        List<Long> prjIdList = FrameUtil.getBeanFieldValues(orderProjectModelList, "project_id");
        Map<Long, ProjectShowInfo> prjMap = projectService.getProjectInfoList(prjIdList);
        for (OrderProjectModel orderProjectModel : orderProjectModelList) {
            ProjectShowInfo projectShowInfo = prjMap.get(orderProjectModel.getProject_id());
            orderProjectModel.getStrMap().put("price", NumberUtil.formatNumber(orderProjectModel.getProject_price(), NumberUtil.FORMAT_4));
            orderProjectModel.getStrMap().put("payment", NumberUtil.formatNumber(orderProjectModel.getPayment(), NumberUtil.FORMAT_4));
            orderProjectModel.getStrMap().put("loan_price", NumberUtil.formatNumber(orderProjectModel.getLoan_price(), NumberUtil.FORMAT_4));
            if(projectShowInfo!=null){
                orderProjectModel.getStrMap().put("prj_name", projectShowInfo.getProject_name());
                orderProjectModel.getStrMap().put("org_name", projectShowInfo.getOrg_name());
                orderProjectModel.getStrMap().put("dc_name", projectShowInfo.getDc_name());
            }
        }
        UserSession userSession = userService.getUserSession(orderModel.getUser_id());

        // 用户芝麻信息
        ZhimaCreditDataModel zhimaInfo = zhimaCreditService.zhimaData(userSession.getUser_id());
        zhimaInfo.getStrMap().put("creditLabel", CreditIndustryLevel.parse(zhimaInfo.getIndustry_level()).getLabel());

        Long currTime =  FrameUtil.getTime(null);
        List<RepaymentDataModel> repaymentDataModelList = repaymentDataService.getModelList(FrameUtil.newHashMap("order_id", order_id), DbWREnums.READ);
        for(RepaymentDataModel repaymentDataModel : repaymentDataModelList){
            OverdueDto overdueDto = RepaymentUtils.overdueInterest(repaymentDataModel.getRepayment_amount(),repaymentDataModel.getEstimation_repayment_time(),currTime);
            if(overdueDto!=null){
                repaymentDataModel.getStrMap().put("overdueDay",overdueDto.getOverdueDay());
                repaymentDataModel.getStrMap().put("overduePrice",overdueDto.getOverduePrice());
            }else {
                repaymentDataModel.getStrMap().put("overdueDay",0);
                repaymentDataModel.getStrMap().put("overduePrice",0);
            }
        }

        request.setAttribute("orderModel", orderModel);//设置订单信息
        request.setAttribute("user", userSession);//设置用户信息
        request.setAttribute("zhimaInfo", zhimaInfo);
        request.setAttribute("orderProjectModelList", orderProjectModelList);//订单项目列表
        request.setAttribute("repaymentDataModelList", repaymentDataModelList);//还款报表列表
        return "order.detail";
    }


    /**
     * 订单首付 支付功能
     * @param order_id
     * @throws Exception
     */
    @RequestMapping("fristPay/{order_id}")
    public void fristPay(@PathVariable("order_id") Long order_id) throws Exception {
        if (order_id == null) {
            FrameUtil.throwBaseException1("参数不能为空");
        }
        orderService.firstPaymentSuccess(order_id);
        successMsg("首付已完成");
    }

    /**
     * 还款（后台帮助用户点击还款功能）
     * @param repayment_id
     * @throws Exception
     */
    @RequestMapping("repayment/{repayment_id}")
    public void repayment(@PathVariable("repayment_id") Long repayment_id) throws Exception {
        if (repayment_id == null) {
            FrameUtil.throwBaseException1("参数不能为空");
        }
        repaymentDataService.repayment(repayment_id);
        successMsg("还款成功");
    }

    /**
     * 还款报表列表，显示订单即将要还的那一期的基本情况
     * @throws Exception
     */
    @RequestMapping("repayment/list")
    public String repaymentList() throws Exception {
        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);
//        paramMap.put("sort", "create_time desc");
//        paramMap.put("repayment_status", "0");
//        paramMap.put("limit_pay", "1");
        paramMap.put("rows", "20");
        PagerHtmlModel pager = PagerUtil.getPagerHtmlModel(
                this.repaymentDataService.getRepaymentList(paramMap, DbWREnums.READ), paramMap,
                ServletUtil.getUrl("/order/repayment/list"));

        OverdueDto overdueDto = null;
        RepaymentDto repayment = null;
        Long current = FrameUtil.getTime();
        for(Object obj : pager.getPagerModel().getDataList()){
            repayment = (RepaymentDto) obj;
            repayment.getStrMap().put("estimation_repayment_time", DateUtil.timestampToDateString(repayment.getEstimation_repayment_time(), DateUtil.PATTERN_yyyy_MM_dd_HH_mm_ss));
            if( repayment.getRepayment_status() == 0 && repayment.getEstimation_repayment_time() < current ){
                overdueDto = RepaymentUtils.overdueInterest(repayment.getRepayment_amount(),repayment.getEstimation_repayment_time(),current);
                repayment.getStrMap().put("overdueDay", overdueDto.getOverdueDay());
                repayment.setOverdue_price(overdueDto.getOverduePrice());
            }
        }

        request.setAttribute("maps", paramMap);
        request.setAttribute("pager", pager);
        return "repayment.list";
    }

    /**
     * 减免金额
     * @param repayment_id
     * @throws Exception
     */
    @RequestMapping("discount")
    public void discount(Long repayment_id,Double price) throws Exception {
        if (repayment_id == null|| price == null) {
            FrameUtil.throwBaseException1("参数不能为空");
        }
        repaymentDataService.discount(repayment_id,price);
        successMsg("减免设置成功");
    }


}
